package com.mall.controller;

import com.mall.pojo.*;
import com.mall.service.CartService;
import com.mall.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/member/order")
public class OrderController {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    private CartService cartService;
    
    @Autowired
    private OrderService orderService;
    
    // 获取结算页信息
    @GetMapping("/pre")
    public Result getCheckoutInfo(@RequestParam("userId") Long userId) {
        try {
            System.out.println("获取结算页信息，用户ID: " + userId);
            
            // 1. 查询购物车中选中的商品
            List<Map<String, Object>> cartItems = jdbcTemplate.queryForList(
                "SELECT c.*, g.name, g.price, g.image FROM cart c " +
                "JOIN goods g ON c.sku_id = g.id " +
                "WHERE c.user_id = ? AND c.checked = 1", userId);
            
            System.out.println("查询到选中的购物车商品数量: " + cartItems.size());
            
            if (cartItems.isEmpty()) {
                // 如果没有选中的商品，则查询所有购物车商品并设置为选中
                System.out.println("没有选中的商品，尝试查询所有购物车商品");
                cartItems = jdbcTemplate.queryForList(
                    "SELECT c.*, g.name, g.price, g.image FROM cart c " +
                    "JOIN goods g ON c.sku_id = g.id " +
                    "WHERE c.user_id = ?", userId);
                
                System.out.println("查询到的所有购物车商品数量: " + cartItems.size());
                
                if (cartItems.isEmpty()) {
                    return Result.error("购物车为空，请先添加商品");
                }
                
                // 更新购物车商品为选中状态
                jdbcTemplate.update(
                    "UPDATE cart SET checked = 1 WHERE user_id = ?", 
                    userId);
                System.out.println("已更新所有购物车商品为选中状态");
            }
            
            // 2. 转换为前端需要的格式
            List<CartItem> goods = new ArrayList<>();
            BigDecimal totalPrice = BigDecimal.ZERO;
            
            for (Map<String, Object> item : cartItems) {
                CartItem cartItem = new CartItem();
                cartItem.setId(((Number)item.get("id")).longValue());
                cartItem.setUserId(((Number)item.get("user_id")).longValue());
                cartItem.setSkuId(((Number)item.get("sku_id")).longValue());
                cartItem.setCount((Integer)item.get("count"));
                cartItem.setSelected(true); // 确保选中状态
                cartItem.setName((String)item.get("name"));
                cartItem.setPicture((String)item.get("image"));
                
                // 设置价格
                BigDecimal price = BigDecimal.valueOf(((Number)item.get("price")).doubleValue());
                cartItem.setPrice(price);
                
                // 计算小计
                BigDecimal itemTotal = price.multiply(BigDecimal.valueOf(cartItem.getCount()));
                totalPrice = totalPrice.add(itemTotal);
                
                // 设置小计和实付总额
                cartItem.setTotalPrice(itemTotal);
                cartItem.setTotalPayPrice(itemTotal);
                
                goods.add(cartItem);
                System.out.println("添加商品到结算页: ID=" + cartItem.getSkuId() + ", 名称=" + cartItem.getName());
            }
            
            // 3. 查询用户地址
            List<Map<String, Object>> addressMaps = jdbcTemplate.queryForList(
                "SELECT * FROM address WHERE user_id = ?", userId);
            
            System.out.println("查询到的地址数量: " + addressMaps.size());
            
            List<Address> addresses = new ArrayList<>();
            for (Map<String, Object> addrMap : addressMaps) {
                Address address = new Address();
                address.setId(((Number)addrMap.get("id")).longValue());
                address.setUserId(((Number)addrMap.get("user_id")).longValue());
                address.setReceiver((String)addrMap.get("receiver"));
                address.setContact((String)addrMap.get("contact"));
                address.setProvinceCode((String)addrMap.get("province_code"));
                address.setCityCode((String)addrMap.get("city_code"));
                address.setCountyCode((String)addrMap.get("county_code"));
                address.setAddress((String)addrMap.get("address"));
                address.setIsDefault((Integer)addrMap.get("is_default"));
                address.setFullLocation((String)addrMap.get("full_location"));
                
                addresses.add(address);
                System.out.println("添加地址: ID=" + address.getId() + ", 收件人=" + address.getReceiver());
            }
            
            // 如果没有地址记录，生成一个测试地址
            if (addresses.isEmpty()) {
                System.out.println("没有查询到地址，创建测试地址");
                
                // 先尝试执行示例数据SQL脚本
                try {
                    System.out.println("尝试插入示例地址数据");
                    jdbcTemplate.update(
                        "INSERT INTO address (id, user_id, receiver, contact, province_code, city_code, county_code, address, is_default, full_location) " +
                        "VALUES (1, ?, '测试用户', '13800138000', '110000', '110100', '110101', '朝阳区测试地址', 0, '北京市 北京市 朝阳区') " +
                        "ON DUPLICATE KEY UPDATE user_id = ?",
                        userId, userId);
                    
                    // 再次查询地址
                    addressMaps = jdbcTemplate.queryForList(
                        "SELECT * FROM address WHERE user_id = ?", userId);
                    
                    for (Map<String, Object> addrMap : addressMaps) {
                        Address address = new Address();
                        address.setId(((Number)addrMap.get("id")).longValue());
                        address.setUserId(((Number)addrMap.get("user_id")).longValue());
                        address.setReceiver((String)addrMap.get("receiver"));
                        address.setContact((String)addrMap.get("contact"));
                        address.setProvinceCode((String)addrMap.get("province_code"));
                        address.setCityCode((String)addrMap.get("city_code"));
                        address.setCountyCode((String)addrMap.get("county_code"));
                        address.setAddress((String)addrMap.get("address"));
                        address.setIsDefault((Integer)addrMap.get("is_default"));
                        address.setFullLocation((String)addrMap.get("full_location"));
                        
                        addresses.add(address);
                        System.out.println("新增地址: ID=" + address.getId() + ", 收件人=" + address.getReceiver());
                    }
                } catch (Exception e) {
                    System.err.println("插入示例地址数据失败: " + e.getMessage());
                }
                
                // 如果仍然没有地址，创建一个临时地址对象
                if (addresses.isEmpty()) {
                    Address testAddress = new Address();
                    testAddress.setId(1L);
                    testAddress.setUserId(userId);
                    testAddress.setReceiver("测试用户");
                    testAddress.setContact("13800138000");
                    testAddress.setAddress("测试地址详情");
                    testAddress.setIsDefault(0);
                    testAddress.setFullLocation("广东省 深圳市 南山区");
                    
                    addresses.add(testAddress);
                    System.out.println("添加临时测试地址");
                }
            }
            
            // 4. 组装结算信息
            CheckoutInfo checkoutInfo = new CheckoutInfo();
            checkoutInfo.setGoods(goods);
            checkoutInfo.setUserAddresses(addresses);
            
            // 5. 订单汇总信息
            OrderSummary summary = new OrderSummary();
            summary.setGoodsCount(goods.stream().mapToInt(CartItem::getCount).sum());
            summary.setTotalPrice(totalPrice);
            summary.setPostFee(new BigDecimal("10.00")); // 固定运费
            summary.setTotalPayPrice(totalPrice.add(summary.getPostFee()));
            
            checkoutInfo.setSummary(summary);
            
            System.out.println("结算信息准备完成，商品数量: " + goods.size() + ", 地址数量: " + addresses.size());
            
            return Result.success(checkoutInfo);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取结算信息失败: " + e.getMessage());
        }
    }
    
    // 创建订单
    @PostMapping
    public Result createOrder(@RequestBody Map<String, Object> orderInfo) {
        try {
            System.out.println("创建订单，信息: " + orderInfo);
            
            // 1. 提取订单基本信息
            Long userId = Long.valueOf(orderInfo.get("userId").toString());
            Long addressId = Long.valueOf(orderInfo.get("addressId").toString());
            Integer deliveryTimeType = (Integer) orderInfo.get("deliveryTimeType");
            Integer payType = (Integer) orderInfo.get("payType");
            Integer payChannel = (Integer) orderInfo.get("payChannel");
            String buyerMessage = (String) orderInfo.get("buyerMessage");
            
            // 2. 查询购物车中选中的商品
            List<Map<String, Object>> cartItems = jdbcTemplate.queryForList(
                "SELECT c.*, g.name, g.price, g.image FROM cart c " +
                "JOIN goods g ON c.sku_id = g.id " +
                "WHERE c.user_id = ? AND c.checked = 1", userId);
            
            if (cartItems.isEmpty()) {
                return Result.error("没有选中的商品");
            }
            
            // 3. 使用OrderService创建订单
            Order order = orderService.createOrder(
                userId, addressId, deliveryTimeType, payType, payChannel, buyerMessage, cartItems);
            
            return Result.success(order);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建订单失败: " + e.getMessage());
        }
    }
    
    // 获取订单详情
    @GetMapping("/{id}")
    public Result getOrderDetail(@PathVariable("id") Long orderId, @RequestParam("userId") Long userId) {
        try {
            System.out.println("获取订单详情，订单ID: " + orderId + ", 用户ID: " + userId);
            
            // 使用OrderService获取订单详情
            Order order = orderService.getOrderDetail(orderId, userId);
            
            if (order == null) {
                return Result.error("订单不存在");
            }
            
            return Result.success(order);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取订单详情失败: " + e.getMessage());
        }
    }
    
    // 模拟支付
    @PostMapping("/pay")
    public Result payOrder(@RequestBody Map<String, Object> payInfo) {
        try {
            System.out.println("支付订单，信息: " + payInfo);
            
            Long orderId = Long.valueOf(payInfo.get("orderId").toString());
            Long userId = Long.valueOf(payInfo.get("userId").toString());
            
            // 使用OrderService支付订单
            boolean success = orderService.payOrder(orderId, userId);
            
            if (!success) {
                return Result.error("支付失败，订单不存在");
            }
            
            return Result.success("支付成功");
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("支付失败: " + e.getMessage());
        }
    }
} 